/* Copyright (c) 2009 - 2010 98Labs Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sbal89.map.util;

import static com.sbal89.map.util.BaseUtil.SI_NAME;
import static com.sbal89.map.util.BaseUtil.U_NAME;
import static com.sbal89.map.util.BaseUtil.U_PASS;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.docs.DocumentEntry;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.PresentationEntry;
import com.google.gdata.util.ServiceException;

/**
 * This is a utility class or helper for Google's
 * Documents List Data API functionalities.
 *  
 */
public class DLDAUtil {
	private static final String DOCS_FEED_URL = "http://docs.google.com/feeds/default/private/full/";

	/**
	 * Used for testing purposes only.
	 * 
	 * @param args
	 * @throws IOException
	 * @throws ServiceException
	 */
    public static void main(String[] args) throws IOException, ServiceException {
    	//String filename = "sheet-02";
    	String googleEmail = "fsdfgsfg@gmail.com";
    	
        DocsService client = new DocsService(SI_NAME);
		client.setUserCredentials(U_NAME, U_PASS);
		
    	DocumentListEntry doc = getAllDocs(client).get(2);
    	System.out.println(doc.getTitle());
    	System.out.println(isDocSharedTo(client, doc, googleEmail));

//    	System.out.println("Uploading " + FILE_PATH  + " to " + filename+"1");
//    	doc = uploadDoc(FILE_PATH, filename+"1");
//    	doc = saveDoc(client, doc);
//    	System.out.println(doc.getDocId());
//    	System.out.println("Sharing...");
//    	shareDoc(client, doc, googleEmail);
//    	System.out.println("Un-sharing...");
//    	unshareDoc(client, doc, googleEmail);

//    	System.out.println("Creating new blank document: " + filename+"2");
//    	doc = newBlankDoc("accounts", "spreadsheet");
//    	System.out.println(saveDoc(client, doc).getDocId());

    	System.out.println("Done");
    }
    
    public static DocumentListEntry getDocByKey(DocsService docService, String resourceId)
		throws MalformedURLException, IOException, ServiceException {
    	return docService.getEntry(new URL(DOCS_FEED_URL + resourceId), DocumentListEntry.class);
    }
    
	public static void delete(DocsService docService, String resourceId)
			throws MalformedURLException, IOException, ServiceException {
		docService.delete(new URL(DOCS_FEED_URL + resourceId + "?delete=true"),
				"*");
	}
    
    public static List<DocumentListEntry> getAllDocs(DocsService docService) throws IOException, ServiceException{
	  URL feedUri = new URL(DOCS_FEED_URL);
	  DocumentListFeed feed = docService.getFeed(feedUri, DocumentListFeed.class);
	  return feed.getEntries();
    }

	public static DocumentListEntry saveDoc(DocsService docService,
			DocumentListEntry doc) throws MalformedURLException, IOException,
			ServiceException {
		return docService.insert(new URL(DOCS_FEED_URL), doc);
	}
	
	public static DocumentListEntry newBlankDoc(String title, String type)
			throws IOException, ServiceException {
		DocumentListEntry newEntry = null;
		if (type.equals("document")) {
			newEntry = new DocumentEntry();
		} else if (type.equals("presentation")) {
			newEntry = new PresentationEntry();
		} else if (type.equals("spreadsheet")) {
			newEntry = new com.google.gdata.data.docs.SpreadsheetEntry();
		}
		newEntry.setTitle(new PlainTextConstruct(title));

		// Prevent collaborators from sharing the document with others?
		// newEntry.setWritersCanInvite(false);

		// You can also hide the document on creation
		// newEntry.setHidden(true);

		return newEntry;
	}
    
	public static DocumentListEntry uploadDoc(String filepath, String title) {
		File file = new File(filepath);
		String mimeType = DocumentListEntry.MediaType.fromFileName(
				file.getName()).getMimeType();

		DocumentListEntry newDocument = new DocumentListEntry();
		newDocument.setFile(file, mimeType);
		newDocument.setTitle(new PlainTextConstruct(title));

		// Prevent collaborators from sharing the document with others?
		// newDocument.setWritersCanInvite(false);

		return newDocument;
	}

	public static boolean isDocSharedTo(DocsService docService,
			DocumentListEntry document, String account)
			throws MalformedURLException, IOException, ServiceException {
		boolean isShared = false;
		AclFeed aclFeed = docService.getFeed(new URL(document.getAclFeedLink()
				.getHref()), AclFeed.class);
		for (AclEntry entry : aclFeed.getEntries()) {
//			System.out.println(entry.getScope().getValue() + " ("
//					+ entry.getScope().getType() + ") : "
//					+ entry.getRole().getValue());
			if (entry.getScope().getValue().equals(account)) {
				isShared = true;
				break;
			}
		}
		return isShared;
	}
	
	public static void shareDoc(DocsService docService,
			DocumentListEntry document, String account)
			throws MalformedURLException, IOException, ServiceException {
		
		// Add a writer/collaborator to document
		AclEntry aclEntry = createAclEntry(account);
		docService.insert(new URL(document.getAclFeedLink().getHref()),
				aclEntry);
	}
	
	public static void unshareDoc(DocsService docService,
			DocumentListEntry document, String account)
			throws MalformedURLException, IOException, ServiceException {
		
		// Remove a writer/collaborator to document
		AclEntry aclEntry = createAclEntry(account);
		docService.delete(new URL(document.getAclFeedLink().getHref()),
				aclEntry.getScope());
	}
	
	private static AclEntry createAclEntry(String account) {
		AclScope scope = new AclScope(AclScope.Type.USER, account);
		AclEntry aclEntry = new AclEntry();
		aclEntry.setRole(AclRole.WRITER);
		aclEntry.setScope(scope);
		return aclEntry;
	}
}
